//
//  HMNetworkTools.swift
//  Swift网络请求封装
//
//  Created by Apple on 16/12/1.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit
import AFNetworking

//  网络请求类型
enum RequestType {
    //  get请求
    case get
    //  post请求
    case post
}



//  网络请求工具类
class HMNetworkTools: AFHTTPSessionManager {

    //  给类型起别名
    typealias CallBack = (Any?, Error?)->()
    
    //  单例全局访问点
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        //  添加可以接受响应数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    
    //  封装get/post
    func request(type: RequestType, url: String, params: Any?, callBack: @escaping CallBack) {
        
        if type == .get {
            get(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response, nil)
            }, failure: { (_, error) in
                callBack(nil, error)
            })
        } else {
            post(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response, nil)
            }, failure: { (_, error) in
                callBack(nil, error)
            })
        }
        
    
    }
    
    
}

//  MARK: -- 发微博相关接口
extension HMNetworkTools {
    
    func upload(status: String, image: UIImage, callBack: @escaping CallBack) {
        //  接口地址
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        let params = [
            "access_token": HMUserAccountViewModel.sharedUserAccount.accessToken!,
            "status": status
        ]
        //  下面两种方法都是把图片转成二进制 ,建议如果图片要求的不是特别高, 建议UIImageJPEGRepresentation
//        let imageData = UIImagePNGRepresentation(image)!
//        (imageData as NSData).write(toFile: "/Users/apple/Desktop/1.png", atomically: true)
        //  compressionQuality 表示图片的质量系数, 系数越大图片的质量越高
        let imageData = UIImageJPEGRepresentation(image, 0.5)!
//        (imageData as NSData).write(toFile: "/Users/apple/Desktop/2.jpg", atomically: true)
        
        
        
        
        //  上传图片的操作
        post(url, parameters: params, constructingBodyWith: { (formData)-> Void in
            //  withFileData: 资源对应的二进制
            //  name: 服务端需要的参数名
            //  fileName: 上传的文件名(一般可以随便写,服务端不会使用我们的名字, 服务端自己会生成唯一的图片名)
            //  mimeType: 资源类型 (application/octet-stream	通用资源类型, 在不确定数据类型的是可以使用)
            formData.appendPart(withFileData: imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
            
        }, progress: nil, success: { (_, response) -> Void in
            
            callBack(response, nil)
        }, failure: { (_, error) -> Void in
            callBack(nil, error)
        })
        
        
    }

    /// 发文字微博接口
    ///
    /// - Parameters:
    ///   - status: 微博内容
    ///   - callBack: 回调的闭包
    func update(status: String, callBack: @escaping CallBack) {
        //  接口地址
        let url = "https://api.weibo.com/2/statuses/update.json"
        let params = [
            "access_token": HMUserAccountViewModel.sharedUserAccount.accessToken!,
            "status": status
        ]
        
        //  执行接口请求
        request(type: .post, url: url, params: params, callBack: callBack)
    
    }
    

}


//  MARK: -- 首页相关的微博接口
extension HMNetworkTools {
    //  请求登录用户所关注的微博接口
    func requestStatus(maxid: Int64, sinceId: Int64, callBack: @escaping CallBack) {
        //  请求的接口地址
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //  请求参数
        let params: [String: Any] = [
            "access_token": HMUserAccountViewModel.sharedUserAccount.accessToken!,
            "max_id": maxid,
            "since_id": sinceId
        ]
        
        let path = url + "?access_token=" + HMUserAccountViewModel.sharedUserAccount.accessToken!
        print(path)
        
        //  执行网络请求
        request(type: .get, url: url, params: params, callBack: callBack)
        
    
    }

}



//  MARK: -- OAuth登陆相关的接口
extension HMNetworkTools {
    
    
    /// 获取用户信息
    ///
    /// - Parameters:
    ///   - accessToken: 令牌
    ///   - uid: 用户id
    ///   - callBack: 回调闭包
    func requestUserInfo(accessToken: String, uid: Int64, callBack: @escaping CallBack) {
        //  请求地址
        let url = "https://api.weibo.com/2/users/show.json"
        //  请求参数
        let params: [String: Any] = [
            "access_token": accessToken,
            "uid": uid
        ]
        
        request(type: .get, url: url, params: params, callBack: callBack)
    
    }
    
    
    
    //  请求accesstoken
    func requestAccesstoken(code: String, callBack: @escaping CallBack) {
        //  请求地址
        let url = "https://api.weibo.com/oauth2/access_token"
        //  请求参数
        let params = [
            "client_id": AppKey,
            "client_secret": AppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": Redirect_uri
        ]
        request(type: .post, url: url, params: params, callBack: callBack)
        
        
    }
    

}








